package com.aliyun.dingtalk.service.impl;

import com.aliyun.dingtalk.service.DingTalkUserService;
import com.aliyun.dingtalk.service.UserCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserCacheServiceImpl implements UserCacheService {

    @Autowired
    private DingTalkUserService dingTalkUserService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ALL_USERS_CACHE_KEY = "users:all_with_details";

    /**
     * 每10分钟同步一次所有用户详细信息到Redis
     */
    @Scheduled(fixedRate = 600000) // 600000毫秒 = 10分钟
    public void syncAllUsersToCache() {
        try {
            // 调用服务获取所有用户详细信息
            Object allUsersData = dingTalkUserService.getAllUsersWithDetails();

            // 存储到Redis，设置过期时间24小时
            redisTemplate.opsForValue().set(ALL_USERS_CACHE_KEY, allUsersData, 24, TimeUnit.HOURS);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从Redis获取缓存的所有用户详细信息
     */
    public Object getCachedAllUsers() {
        return redisTemplate.opsForValue().get(ALL_USERS_CACHE_KEY);
    }


    /**
     * 手动触发同步所有用户详细信息到Redis
     */
    public void manualSyncAllUsersToCache() {
        try {
            // 调用服务获取所有用户详细信息
            Object allUsersData = dingTalkUserService.getAllUsersWithDetails();

            // 存储到Redis，设置过期时间24小时
            redisTemplate.opsForValue().set(ALL_USERS_CACHE_KEY, allUsersData, 24, TimeUnit.HOURS);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("手动同步用户数据失败: " + e.getMessage());
        }
    }
}
